package com.martin.fast_frame_compose.base

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavOptionsBuilder
import com.martin.fast_frame_compose.page.main.MainActivity
import com.martin.fast_frame_compose.page.main.MainViewModel
import com.martin.lib_base.interfaces.ILoading
import com.martin.lib_base.ktx.loge
import dev.DevUtils

/**
 * @author：孟凡华
 * @date：2022/11/11
 * @desc：
 */
abstract class BaseViewModel : ViewModel(), ILoading, DefaultLifecycleObserver {

    val mainViewModel: MainViewModel by lazy {
        ViewModelProvider(DevUtils.getTopActivity() as MainActivity)[MainViewModel::class.java]
    }

    var router: String = ""

    ///////////////////////////////////////////////////////////////////////////
    // 方法区
    ///////////////////////////////////////////////////////////////////////////

    override fun onCreate(owner: LifecycleOwner) {
        showLog("onCreate")
    }

    override fun onStart(owner: LifecycleOwner) {
        showLog("onStart")
    }

    override fun onResume(owner: LifecycleOwner) {
        showLog("onResume")
    }

    override fun onPause(owner: LifecycleOwner) {
        showLog("onPause")
    }

    override fun onStop(owner: LifecycleOwner) {
        showLog("onStop")
    }

    override fun onDestroy(owner: LifecycleOwner) {
        showLog("onDestroy")
    }

    /**
     * 导航到指定页面
     */
    open fun navigateTo(
        route: String,
        data: Map<String, Any> = emptyMap(),
        builder: NavOptionsBuilder.() -> Unit = {},
    ) {
        dismissLoading()
        mainViewModel.navigateTo(route, data, builder)
    }

    /**
     * 返回
     */
    open fun navigateUp() {
        dismissLoading()
        mainViewModel.navController.navigateUp()
    }

    /**
     * 获取页面数据
     */
    fun getPageData(): Map<String, Any> {
        return mainViewModel.pageData[router] ?: emptyMap()
    }

    /**
     * 校验是否为最上面的页面
     */
    fun verifyIsTopPage(): Boolean {
        return getNavController().currentDestination?.route == router
    }

    private fun getNavController() = mainViewModel.navController

    override fun showLoading() {
        mainViewModel.showLoading()
    }

    override fun dismissLoading() {
        mainViewModel.dismissLoading()
    }

    override fun onCleared() {
        super.onCleared()
        showLog("onCleared")
        dismissLoading()
        mainViewModel.pageData.remove(router)
    }

    private fun showLog(message: String) {
        loge("${this.javaClass.simpleName} : $message")
    }
}